<?php
/**
 *
 *
 * PHP version 5.3.x
 *
 * @category
 * @package
 * @author   gouki <gouki.xiao@gmail.com>
 */
/**
 * SaeFileHelper.php
 *
 * @category
 * @package
 * @author   gouki <gouki.xiao@gmail.com>
 * @version $Id$
 * @created 2011-11-22 00:19
 */
class SaeFileHelper extends CFileHelper
{

	/**
	 * Copies a directory recursively as another.
	 * If the destination directory does not exist, it will be created.
	 * @param string $src the source directory
	 * @param string $dst the destination directory
	 * @param array $options options for directory copy. Valid options are:
	 * <ul>
	 * <li>fileTypes: array, list of file name suffix (without dot). Only files with these suffixes will be copied.</li>
	 * <li>exclude: array, list of directory and file exclusions. Each exclusion can be either a name or a path.
	 * If a file or directory name or path matches the exclusion, it will not be copied. For example, an exclusion of
	 * '.svn' will exclude all files and directories whose name is '.svn'. And an exclusion of '/a/b' will exclude
	 * file or directory '$src/a/b'. Note, that '/' should be used as separator regardless of the value of the DIRECTORY_SEPARATOR constant.
	 * </li>
	 * <li>level: integer, recursion depth, default=-1.
	 * Level -1 means copying all directories and files under the directory;
	 * Level 0 means copying only the files DIRECTLY under the directory;
	 * level N means copying those directories that are within N levels.
 	 * </li>
	 * </ul>
	 */
	public static function copyDirectory($domain,$src,$dst,$options=array())
	{
		$fileTypes=array();
		$exclude=array();
		$level=-1;
		extract($options);
		self::copyDirectoryRecursive($domain,$src,$dst,'',$fileTypes,$exclude,$level,$options);
	}
    /**
     * 将其他目录里的数据拷贝到storage目录中
     * @static
     * @param $domain
     * @param $src
     * @param $dst
     * @param $base
     * @param $fileTypes
     * @param $exclude
     * @param $level
     * @param $options
     * @return void
     */
    protected static function copyDirectoryRecursive($domain,$src, $dst, $base, $fileTypes, $exclude, $level, $options) {
        $saeStorage = new SaeStorage();
		$folder=opendir($src);
		while(($file=readdir($folder))!==false)
		{
			if($file==='.' || $file==='..')
				continue;
			$path=$src.DIRECTORY_SEPARATOR.$file;
			$isFile=is_file($path);
			if(self::validatePath($base,$file,$isFile,$fileTypes,$exclude)){
				if($isFile){
                    if(!$saeStorage->fileExists($domain,$dst.DIRECTORY_SEPARATOR.$file)){
                        $saeStorage->write($domain,$dst.DIRECTORY_SEPARATOR.$file,file_get_contents($path));
                    }
				}
				else if($level)
					self::copyDirectoryRecursive($domain,$path,$dst.DIRECTORY_SEPARATOR.$file,$base.'/'.$file,$fileTypes,$exclude,$level-1,$options);
			}
		}
		closedir($folder);
    }
}
